package com.changhongit.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.shaded.json.parser.JSONParser;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;


import java.security.interfaces.RSAPrivateKey;
import java.util.Date;

public class IdaasInfo {
    //获取kid方式：ServiceAccount中的privateKey的kid
    static String kid="01de24ee-6996-438a-b260-3ef58ce33c00";

    public static String getToken(){


        //该参数由IDaaS提供
        String serviceAccount = "{\n" +
                "    \"clientId\": \"f9b0cc6b-1681-4d76-bd19-6d5425c3b79f\",\n" +
                "    \"privateKey\": {\n" +
                "        \"p\": \"xZ759Z3TPCBBbRkwmMooha0uYuYG2_dleu3D1VBhwWV_lO3x9iV2avB_5qUg1H5Var1eDFdsiubIiYiKMeiT5OcrxsyyALG8YEyoU-Ri4WbNQVLf1dkP-xUhDkAx17Y7hVKBxz6aKRmMYTdHH9_P1zEPb2-LCfiFPsqzHX92TlE\",\n" +
                "        \"kty\": \"RSA\",\n" +
                "        \"q\": \"qLCUq4uQ8fDl_9MBL4pbNZm19ShvQj_OtFuLCeVeM_ZIsmwcgxUgQvC59EKgHg8qbGH_jXXFm-tKM9I3xWYgssccuAVUKpFGfK4ngOAVgWLtvzMdSWojZMZrmcWgNOS1-XYbap-EO_pUFtkzUxVsaou_GImisnnpzfQ-xUEvgv8\",\n" +
                "        \"d\": \"KV-Bk6WlirNEREly1VWfT4nWY80AnsG01KWmoGH3uURcGsq9oMCOeWawA36OT6x0VIcAs-XmtOXzl6SLm2vfTWaSMfyru2ZF0NwKCBZatoBYDHSFf1E1yBRP0ypc3ZLWZAAfkk62Dc43wGa99nn7ycXknjFxJPd2dcNILhKuIct6fOuieRRpMP0vRh7rRHIE0N5b3fzLRv43qluGfpZLrweYcV0K1vXofEDEpKvaHp-3-yiFaOs4RuNQok5EBbpQAPqizF9sfCJnDSbav_F0sRnC0243GwCbY1IpRrVPghq6d7XJDwKC8rMaT_VXs3vM0Y8-R3zJDI0bXxWoiCBiQQ\",\n" +
                "        \"e\": \"AQAB\",\n" +
                "        \"use\": \"sig\",\n" +
                "        \"kid\": \"01de24ee-6996-438a-b260-3ef58ce33c00\",\n" +
                "        \"qi\": \"pi9dHIoNqLGW3JtaJrd3V4Q4P1R9RwszzNCpSFdr68lweP5XE8IvcNESjLfnlIJ0DkvVKHvPtRR5K5UbKJBtL3CI9YPjykJ9ylmbrg7LH7aMKXrmcwbtijZfBtEdnQIWu9_YfWLUirxvoXK_xGqHHGBCPKgKe0ezz-gXaJGBbQY\",\n" +
                "        \"dp\": \"Fe8hOzu7OE80M9G57RtzB_NC1MNHO57n6o79T23Oi9KiKHuIgZOC4zeyWn01eaBUBrbh-2iwqXIYC_vVqthvodZuq3AIyb7wc5fOjxEoUHBCk9-I7IldFrcvpg9F-PVHAfM4aE7weWNWi2vBPy5uOSo-1lWBDyhAUcnZu4psLSE\",\n" +
                "        \"dq\": \"dBXweYz2FkkdPkvKyRiBZAV_flJxHjoi2WMV7510knWt2Xsks-BZ7zcSANHItmbhXuyhnIurjX0B9193GdUKM31qegjQvupyg2KltL6AjiWyTp2yTc9IxBT3_z5M3Zl20VFB1MIpkczXCVI3S7m2fivlOdGdsQzMpPqsJ7qQI6k\",\n" +
                "        \"n\": \"gjikGV3fTOaiuh0Nx5j6e04k53oXZ_fINgdeLX9mHDrJFNy4Kw7qjrskfizS9IBn4Ko5CKmy33nx2yqz2KaNgL-Yb7heIQYKEit128KPnMt73dPpIUDnpdT3qGPufdhDXFCZRVhz0oNTj_PIlyzBg_FTL9oGnpvjvL6wnhh-WJiotydYwTeNtlmdmd8hT6-wMrGmVCfj4xPPAF21tFh9WqRyDPyyq3A9POLR2XkuSUMJyZRX_lVN99yvs-e9RsRmcbPsc8aXZoErN7f0IPQUCPrcGLnzVhTwBjTa4l6ttSiVHb7d-n1VenCTP6k9Cym4WUtYR2kZ-hIZ2rgL_Hwkrw\"\n" +
                "    }\n" +
                "}";
        String jwtToken = generateJWT(serviceAccount);
        System.out.println("Bearer "+jwtToken);
        return "Bearer "+jwtToken;
    }

    /**
     *  生成JWT Token
     * @author XiaohanLiu
     * @param serviceAccount 秘钥字符串
     * @return jwtToken jwt数据
     * @throws Exception
     */
    public static String generateJWT(String serviceAccount) {
         try {
                    //注意：这里获取到的时间戳需要是东8区的当前时间。
         long now = System.currentTimeMillis();
         JSONObject jwkJsonObj = JSON.parseObject(serviceAccount);
         String clientId = jwkJsonObj.getString("clientId");
         RSAPrivateKey privateKey = getPrivateKey(jwkJsonObj.getString("privateKey"));
         JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder()
        .audience("contacts")
         .expirationTime(new Date(now + 1800000))  //Token的过期时间，此处为30分钟。
         .issueTime(new Date(now))
         .issuer(clientId)
        .claim("account_type","serviceAccount");
         JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.parse("RS256"))
        .keyID(kid)
        .type(JOSEObjectType.JWT)
         .build();
        SignedJWT signedJWT = new SignedJWT(header, claimsBuilder.build());
         signedJWT.sign(new RSASSASigner(privateKey));
           return signedJWT.serialize();
         } catch (Exception e) {
         e.printStackTrace();
        }
 return null;
    }

    /**
     * 将秘钥字符串转换成秘钥对象。
     * @author XiaohanLiu
     * @param privateKey 秘钥字符串
     * @return 秘钥对象
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
         Object privateKeyObj = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT |
                        JSONParser.ACCEPT_TAILLING_SPACE).parse(privateKey);
         if (privateKeyObj instanceof com.nimbusds.jose.shaded.json.JSONObject) {
         com.nimbusds.jose.shaded.json.JSONObject jwtObject = (com.nimbusds.jose.shaded.json.JSONObject) privateKeyObj;
         // Find the RSA signing key
         if (jwtObject.get("use").equals("sig") && jwtObject.get("kty").equals("RSA")) {
         return RSAKey.parse(jwtObject).toRSAPrivateKey();
         }
         }
         return null;
    }

}
